import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import mixConfig from './config/index';
import { CommonModule } from '@/common/common.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { CorsMiddleware } from './core/middleware/cors.middleware';
import { IpMiddleware } from './core/middleware/ip.middleware';
import { RedisModule } from './redis/redis.module';
import { Unique, EntityExistsConstraint } from '@/core/validators';
import * as path from 'path';

 
const ENV = process.env.NODE_ENV;

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: path.resolve(process.cwd(), 'env', !ENV ? '.dev.example' : `.env.${ENV}`),
      load: mixConfig,
      isGlobal: true,
    }),
    TypeOrmModule.forRootAsync({
      useFactory: (config: ConfigService) => config.get('database'),
      inject: [ConfigService],
    }),

    // redis 启动
    // RedisModule.forRootAsync({
    //   useFactory: async (configService: ConfigService): Promise<ConfigService> => {
    //     return configService;
    //   },
    //   inject: [ ConfigService ],
    // }),
    CommonModule,
  ],
  providers: [AppService, Unique, EntityExistsConstraint],
})
export class AppModule implements NestModule {
  constructor(private readonly configService: ConfigService) {}

  configure(consumer: MiddlewareConsumer) {
    const middlewares = [
      IpMiddleware,
      CorsMiddleware,
    ];
    consumer
      .apply(...middlewares)
      .forRoutes({ path: '*', method: RequestMethod.ALL });
  }
}
